package com.myself.model.demo.netty.chat;

import cn.hutool.core.util.StrUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.LinkedList;
/**
 * @author Czx
 */
public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

    static LinkedList<Channel> channelList = new LinkedList<>();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelList.add(channel);
        System.out.println(StrUtil.format("用户已上线 IP 地址为:{}", channel.remoteAddress()));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelList.remove(channel);
        System.out.println(StrUtil.format("用户已下线 IP 地址为:{}", channel.remoteAddress()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        Channel sendMessageChannel = ctx.channel();
        for (Channel channel : channelList) {
            if (channel != sendMessageChannel) {
                channel.writeAndFlush(s);
            }
        }
    }
}
